import axios from 'axios';
import qs from 'qs';
import { notification } from 'antd';
import Nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import store from "../redux/store";
import {deleteUserInfo} from "../redux/actions/login_action"

// axios基础url
axios.defaults.baseURL = 'http://localhost:3000';
//为post请求设置默认请求头
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
// 添加一个请求拦截器
axios.interceptors.request.use(config => {
    Nprogress.start();
    if(config.method.toUpperCase() === 'POST' && config.data instanceof Object) {
        config.data = qs.stringify(config.data);
    }
    const admin_jwt_token = window.localStorage.getItem('admin_jwt_token');
    config.headers.Authorization = `Bearer ${admin_jwt_token}`;
    return config;
}, err => {
    return Promise.reject(err);
});
// 添加一个响应拦截器
axios.interceptors.response.use(response => {
    Nprogress.done();
    if (parseInt(response.data.code) === 401) {
        notification['warning']({
            message: '警告',
            description: '登录过期请重新登录'
        });
        store.dispatch(deleteUserInfo());
    }
    if (response.data && response.data.code) {
        if (parseInt(response.data.code) === -1) {
            notification['warning']({
                message: '警告',
                description: '请求失败'
            });
        }
    }
    return response;
}, error => {
    Nprogress.done();
    console.log(error);
    console.dir(error);
    notification['warning']({
        message: '警告',
        description: '服务器连接失败'
    });
    return Promise.reject(error);
});

export default axios;